﻿using System.Linq;
using System.Xml;
using DataScripter.Containers;
using DataScripter.Scripting;
using DataScripter.Scripting.OutputDestinations;

namespace DataScripter.XmlInterpreter.XmlInterpreters
{
    public class OutputDestinationInterpreter : IXmlInterpreter<IOutputDestination>
    {
        private IContainer Container { get; set; }

        public OutputDestinationInterpreter(IContainer container)
        {
            Container = container;
        }

        public IOutputDestination InterpretElement(XmlElement element)
        {
            string name = element.GetAttribute("Name");
            string type = element.GetAttribute("Type");

            IOutputDestination destination = null;
            // TODO: replace with proper factory or IOC magic
            if (type == "File")
            {
                destination = new FileOutputDestination(name, Container);
                InterpretFileOutputDestination(element, (IFileOutputDestination)destination);
            }
            return destination;
        }

        private static void InterpretFileOutputDestination(XmlElement element, IFileOutputDestination destination)
        {
            foreach (XmlElement child in element.ChildNodes.OfType<XmlElement>())
            {
                switch (child.Name)
                {
                    case "Path":
                        string path = child.InnerText;
                        destination.OutputPath = path;
                        break;
                    case "OutputProducer":
                        destination.Register<IOutputProducer>(child);
                        break;
                }
            }
        }
    }
}
